package main

import (
	"context"
	"fmt"
	"grpc-3/helper"
	"grpc-3/pb/services"

	"google.golang.org/grpc"
	"log"
)

//需要拷贝根据 Prod.proto 生成的两个文件( Prod.pb.go Prod_grpc.pb.go )
func main() {
	//chrome页面通过get请求访问
	//http://localhost:8080/v1/prod/135

	//通过rpc访问
	conn, err := grpc.Dial(":8081", grpc.WithTransportCredentials(helper.GetClientCredentials()))
	if err != nil {
		log.Fatalf("连接GRPC服务端失败 %v\n", err)
	}

	defer conn.Close()
	prodClient := services.NewProductServiceClient(conn)

	//获取单个
	getProductStock(err, prodClient)

	//获取多个(列表
	getProductStocks(err, prodClient)

}

func getProductStocks(err error, prodClient services.ProductServiceClient) {
	prods, err := prodClient.GetProductStocks(context.Background(),
		&services.QuerySize{Size: 3})
	if err != nil {
		log.Fatalf("请求GRPC服务端失败 %v\n", err)
	}
	for _, res := range prods.Prodres {
		fmt.Printf("商品库存为: %v\n", res.ProdStock)
	}
}

func getProductStock(err error, prodClient services.ProductServiceClient) {
	prodRes, err := prodClient.GetProductStock(context.Background(),
		&services.ProdRequest{ProdId: 12, ProdArea: services.ProdAreas_B})
	if err != nil {
		log.Fatalf("请求GRPC服务端失败 %v\n", err)
	}
	fmt.Println(prodRes.ProdStock)
}
